import styles from './index.module.css';

import { Form, Input, Button, Card, Grid, Field, Message } from '@alifd/next';
import { useEffect, useState } from 'react';
import { definePageConfig, useAuth, useNavigate, useRequest } from 'ice';
import userService from '@/services/user';

const FormItem = Form.Item;

export const pageConfig = definePageConfig(() => ({
  title: '登录',
}));
export default function IndexPage() {
  // 登录
  const loginRequest = useRequest(userService.login);
  // 注册
  const registerRequest = useRequest(userService.register);
  const navigate = useNavigate();
  const [auth, setAuth] = useAuth();
  const registerForm = Field.useField();
  // 0登录 1注册
  const [model, setModel] = useState<0 | 1>(0);
  const commonProps = {
    title: model ? '注册' : '登录',
    subTitle: '欢迎使用图片管理器😋',
    extra: (
      <Button
        type="primary"
        text
        onClick={() => {
          setModel(model ? 0 : 1);
        }}
      >
        {model ? '已有账户前往登录' : '没有账户前往注册'}
      </Button>
    ),
  };
  const handleSubmit = (values: any, errors: any) => {
    if (!errors) {
      if (model) {
        // 注册
        registerRequest.runAsync(values.name, values.email, values.password).then((result) => {
          if (result.data && result.success) {
            Message.success(`${values.name}注册成功请登录 (●'◡'●)`);
            setModel(0);
          }
        });
      } else {
        // 登录
        loginRequest.runAsync(values.email, values.password).then((result) => {
          if (result.success && result.data) {
            localStorage.setItem('user', JSON.stringify(result.data.user));
            localStorage.setItem('token', result.data.token);
            Message.success(`${result.data.user.name}欢迎您 (●'◡'●)`);
            setAuth({ admin: true });
            navigate('/home');
          }
        }).catch(error => {
          console.log(error);
        });
      }
    }
  };
  // 确认密码校验
  const notarizePasswordValidator = (_rule: any, value: string, callback: (error?: string) => void) => {
    const password = registerForm.getValue('password');
    if (password && value) {
      if (value !== password) {
        callback('密码不一致');
      }
    }
    callback();
  };

  useEffect(() => {
    document.title = model ? '注册' : '登录';
    registerForm.resetToDefault();
    console.log(document.title);
  }, [model, registerForm]);
  return (
    <div className={styles.register}>
      <Grid.Row className="w-full">
        <Grid.Col xs="20" s="10" className="m-0 mx-auto p-x-10px">
          <Card free>
            <Card.Header {...commonProps} />
            <Card.Content>

              <Form
                field={registerForm}
                labelTextAlign="left"
                size="large"
                labelAlign="inset"
              >
                <FormItem name="email" label="邮箱" format="email" required asterisk={false}>
                  <Input />
                </FormItem>
                <FormItem name="password" label="密码" required asterisk={false} minLength={6}>
                  <Input.Password />
                </FormItem>
                {model == 1 &&
                  <>
                    <FormItem
                      name="notarizePassword"
                      label="确认密码"
                      required
                      asterisk={false}
                      validator={notarizePasswordValidator}
                    >
                      <Input.Password />
                    </FormItem>
                    <FormItem
                      name="name"
                      label="昵称"
                      required
                      asterisk={false}
                      maxLength={20}
                    >
                      <Input />
                    </FormItem>
                  </>}
                <FormItem>
                  <Form.Submit
                    className="w-full"
                    type="primary"
                    validate
                    htmlType="submit"
                    onClick={handleSubmit}
                    disabled={loginRequest.loading || registerRequest.loading}
                  >
                    {model ? '注册' : '登录'}
                  </Form.Submit>
                </FormItem>
              </Form>
            </Card.Content>
          </Card>
        </Grid.Col>
      </Grid.Row>
    </div>
  );
}

